package com.example.bee_work_3.collect;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bee_work_3.account.LoginOrRegister;
import com.example.bee_work_3.net_request.MyJsonArray;
import com.example.bee_work_3.net_request.MyJsonObject;
import com.example.bee_work_3.R;
import com.example.bee_work_3.net_request.WS;
import com.example.bee_work_3.webc_ontent.WebActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 用于显示收藏列表等以后肯扩展需要用到的列表展示
 **/
public class ListActivity extends AppCompatActivity {
    private int pager = 0;
    private int lastItem = 0;

    private Button back;
    private TextView title;
    private ListView listView;
    private SwipeRefreshLayout refreshLayout;

    private List<String[]> dataList = new ArrayList<>();
    private ListActivityAdapter adapter;

    private CallBack callBack = new CallBack() {
        @Override
        public void onItemClick(String[] item) {
            Intent data = new Intent(getApplicationContext(), WebActivity.class);
            data.putExtra("title", item[2]);
            data.putExtra("URL", item[4]);
            data.putExtra("id", Integer.parseInt(item[0]));
            startActivity(data);
        }

        @Override
        public void onDelete(int id, int position) {
            deleteItem(id, position);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        init();
        refreshLayout.setRefreshing(true);
        getData();
    }

    public void init() {
        back = findViewById(R.id.back);
        title = findViewById(R.id.title);
        listView = findViewById(R.id.listView);
        refreshLayout = findViewById(R.id.refresh);
        adapter = new ListActivityAdapter(getApplicationContext(), R.layout.item_with_swipe, dataList, callBack);
        listView.setAdapter(adapter);
        Intent data = getIntent();
        String t_title = data.getStringExtra("title");
        title.setText(t_title == null ? "" : t_title);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                adapter.notifyDataSetChanged();     //滑动一次就会刷新列表，使底层的bottomView归位
                if (scrollState == SCROLL_STATE_IDLE && lastItem == dataList.size() - 1) {
                    getData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lastItem = listView.getLastVisiblePosition();
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pager = 0;
                dataList.clear();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
                getData();
            }
        });
    }

    public void getData() {
        WS.CallBack callBack = new WS.CallBack() {
            @Override
            public void onResult(String Json) {
                Log.e("JSON", Json);
                MyJsonObject object = new MyJsonObject(Json);
                object = object.getJsonObject("data");
                if (object.getInt("total") == dataList.size()) {
                    pager--;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ListActivity.this, "没有数据了...", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                MyJsonArray objectList = object.getJsonArray("datas");
                List<MyJsonObject> list = objectList.getList();
                for (MyJsonObject tmp : list) {
                    dataList.add(new String[]{
                            tmp.getString("author"),
                            tmp.getString("title"),
                            tmp.getString("niceDate"),
                            tmp.getString("link")
                    });
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                        if (refreshLayout.isRefreshing()) {
                            refreshLayout.setRefreshing(false);
                        }
                    }
                });
            }
        };
        WS.load("https://www.wanandroid.com/lg/collect/list/" + (pager++) + "/json")
                .addCallBack(callBack)
                .loadCookies(LoginOrRegister.COOKIESNAME)
                .get();
    }

    public void deleteItem(int id, final int position) {
        WS.CallBack callBack = new WS.CallBack() {
            @Override
            public void onResult(String Json) {
                Log.e("Json", Json);
                MyJsonObject object = new MyJsonObject(Json);
                if (object.getInt("errorCode") == 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ListActivity.this, "已取消收藏", Toast.LENGTH_SHORT).show();
                            dataList.remove(position);
                            adapter.notifyDataSetChanged();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ListActivity.this, "错误", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        };
        Collect.delete(id, LoginOrRegister.COOKIESNAME, callBack);
    }

    interface CallBack {
        void onItemClick(String[] item);

        void onDelete(int id, int position);
    }
}
